package com.LeeCode;

import java.util.HashMap;

/**
 * 水果成篮
 */

public class Code904 {
    public static void main(String[] args) {
        int[] fruits = {1, 2, 3, 2, 2};
        System.out.println(new Code904().totalFruit(fruits));
    }

    public int totalFruit(int[] fruits) {
        int ans = 0, left = 0;
        HashMap<Integer, Integer> map = new HashMap<>();

        for (int right = 0; right < fruits.length; right++) {
            map.merge(fruits[right], 1, Integer::sum);
            while (map.size() > 2) {
                map.merge(fruits[left], -1, (oldVal, delta) -> {
                    int res = oldVal + delta;
                    return res == 0 ? null : res;
                });
                left++;
            }
            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }
}
